﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ClassLibrary
{
    /// <summary>
    /// 以大端方式读取数据，只进只读
    /// </summary>
    public class BigendianReader
    {
        public BigendianReader(byte[] byteData,int startIndex=0)
        {
            this.data = byteData;
            this.currentIndex = startIndex;
            this.encoder = Encoding.GetEncoding("GBK");
        }

        private Encoding encoder;

        byte[] data;

        /// <summary>
        /// 当前索引位置
        /// </summary>
        int currentIndex;


        public string ReadOctetString(int length)
        {
            string value = encoder.GetString(data, currentIndex, length).Replace("\0", "");
            currentIndex += length;
            return value;
        }

        public DateTime ReadByte7DateTime()
        {
            //年转小端
            Array.Reverse(data, currentIndex + 2, 2);

            DateTime value = new DateTime(
                BitConverter.ToInt16(data, currentIndex + 2),
                data[currentIndex + 1],
                data[currentIndex],
                data[currentIndex + 4],
                data[currentIndex + 5],
                data[currentIndex + 6]
                );
            currentIndex += 7;
            return value;
        }

        public UInt16 ReadUInt16()
        {
            Array.Reverse(data, currentIndex, 2);
            UInt16 value = BitConverter.ToUInt16(data, currentIndex);
            currentIndex += 2;
            return value;
        }

        public UInt32 ReadUInt32()
        {
            
            Array.Reverse(data, currentIndex, 4);
            UInt32 value = BitConverter.ToUInt32(data, currentIndex);
            currentIndex += 4;
            return value;
        }

        public byte ReadByte()
        {
            byte value = data[currentIndex];
            currentIndex += 1;
            return value;
        }

        public byte[] ReadBytes(int count)
        {
            byte[] value = new byte[count];
            Buffer.BlockCopy(data, currentIndex, value, 0, count);
            currentIndex += count;
            return value;
        }

        public DateTime ReadTime_t()
        {
            DateTime value = new DateTime(BitConverter.ToInt64(data, currentIndex));
            currentIndex+=8;
            return value;
        }


        public DateTime ReadUtcTime()
        {
            DateTime utc = DateTime.Parse("1970-1-1 0:0:00");
            Array.Reverse(data, currentIndex, 8);
            long diffseconds = BitConverter.ToInt64(data, currentIndex);
            DateTime dt = utc.AddSeconds(diffseconds);
            currentIndex += 8;
            return dt.ToLocalTime();
        }
    }
}
